package com.dituhui.tool.gis;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.HttpTool;
import com.dituhui.tool.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 地址解析
 * 
 * @author liweigu
 *
 */
public class Geocoder {
	private static Logger LOGGER = Logger.getLogger(Geocoder.class);
	private static final String AMAP_GEOCODE_URL = Constants.getValue("amapGeocodeUrl", "config.properties");
	private static final String KEY = "10d58a522366d2c2e8de07852e7ad59d";

	/**
	 * 地址匹配
	 * 
	 * @param address 地址
	 * @return 坐标点
	 */
	public static Point geocode(String address) {
		Point point = null;

		String path = AMAP_GEOCODE_URL;
		String param = "key=" + KEY + "&address=" + address;
		try {
			String result = HttpTool.getContentByGET(path, param);
			if (result != null) {
				JSONObject jsonObject = JSONObject.fromObject(result);
				int status = jsonObject.getInt("status");
				// 1表示请求成功
				if (status == 1) {
					JSONArray geocodes = jsonObject.getJSONArray("geocodes");
					if (geocodes.size() > 0) {
						JSONObject geocode = geocodes.getJSONObject(0);
						String location = geocode.getString("location");
						String[] arr = location.split(StringUtil.COMMA);
						double x = Double.parseDouble(arr[0]);
						double y = Double.parseDouble(arr[1]);
						point = new Point(x, y);
					}
				}
			}
		} catch (IOException e) {
			LOGGER.info("geocode发送异常。param=" + param, e);
		}

		return point;
	}
}
